<script setup>
import { useUserStore } from '@/stores/user';
// eslint-disable-next-line no-unused-vars
import { Toast } from 'vant';
import api4j from '@/api/example';
import { EiInfo } from '@eplat/ei';
import JWeixin from 'weixin-js-sdk';
import { queryUrlParam } from '@/utils/tools';
const router = useRouter();
// eslint-disable-next-line no-unused-vars
const user = useUserStore();
// data
const username = ref('');
const tel = ref('');
// 存放最终的资产数据
let zcData = [];
let zcDatas = [];

// eslint-disable-next-line no-unused-vars
const onSubmit = async () => {
  console.log('zcData:', zcData);
  console.log('zcDatas:', zcDatas);
  if (fieldValue1.value === '' || fieldValue1.value === undefined) {
    Toast('请选择楼层');
    return;
  }
  if (val8.value === '' || val8.value === undefined) {
    Toast('资产不能为空');
    return;
  }

  if (username.value === '' || username.value === undefined) {
    Toast('请绑定姓名');
    return;
  }
  if (tel.value === '' || tel.value === undefined) {
    Toast('请绑定电话');
    return;
  }
  const postEiInfo = new EiInfo();
  postEiInfo.set(
    'zc',
    zcData.filter((item) => item.assetName === val8.value)
  );
  postEiInfo.set('username', username.value);
  postEiInfo.set('tel', tel.value);
  postEiInfo.set('token', user.getToken);
  postEiInfo.set('zcData', zcDatas);

  await api4j.RCRM0103_userZCBD(postEiInfo).then((res) => {
    if (res.status == -1) {
      Toast(res.msg);
      return;
    }
    Toast(res.msg);
    // 缓存
    user.setUserNameTel(username.value, tel.value);
    zcClear();
    router.push('/WX/WD/WXWD02');
  });
};

// 授权
JWeixin.config({
  debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
  appId: api4j.APPID, // 必填，公众号的唯一标识
  timestamp: '', // 必填，生成签名的时间戳
  nonceStr: '', // 必填，生成签名的随机串
  signature: '', // 必填，签名
  jsApiList: [] // 必填，需要使用的JS接口列表
});
JWeixin.ready(async () => {
  // 获取用户code
  const code = queryUrlParam('code');
  // 没有授权code
  if (code == null) {
    // // Toast('授权失败');
    // 跳转到授权页面
    window.location.href =
      'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
      api4j.APPID +
      '&redirect_uri=https%3A%2F%2F' +
      api4j.SERVER_DOMAIN +
      '%2F%23%2FWX%2FWD%2FWXWD01&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
  } else {
    // 本地没有token新授权
    // console.log('进入方法之前:',user.getToken)
    // eslint-disable-next-line eqeqeq
    if (user.getToken == '' || user.getToken == undefined) {
      // // Toast('正在授权');
      // console.log('进入方法:',user.getToken)
      const postEiInfo = new EiInfo();
      postEiInfo.set('code', code);
      // 通过code获取用户信息
      await api4j.wxLogin(postEiInfo).then((res) => {
        // 如果授权无效 重新授权
        if (res.status !== 1) {
          // Toast(res.msg);
          window.location.href =
            'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
            api4j.APPID +
            '&redirect_uri=https%3A%2F%2F' +
            api4j.SERVER_DOMAIN +
            '%2F%23%2FWX%2FWD%2FWXWD01&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
          return;
        }
        // Toast(res.msg);
        // token info存放本地
        user.setUserInfo(
          res.extAttr.token,
          res.extAttr.userInfo.attrs.headimgurl,
          res.extAttr.userInfo.attrs.nickname
        );
        user.setUserNameTel(res.extAttr.username, res.extAttr.phone);
        // console.log('132',user.getToken)
        // console.log(user.getHeadimgurl)
        // console.log(user.getNickname)
        // console.log('qqqq', res)
        // 资产不存在,跳转页面进行绑定
        // eslint-disable-next-line eqeqeq
        if (res.msg == '授权无资产') {
          router.push('/WX/WD/WXWD01');
        }
      });
    }
  }
});
// 选项列表，children 代表子选项，支持多级嵌套
// eslint-disable-next-line no-unused-vars
const options = [
  {
    label: '浙江省',
    id: '330000',
    parentId: '1231312',
    children: [
      {
        label: '杭州市',
        id: '330100',
        parentId: '687',
        children: [
          {
            label: '杭州市',
            id: '330100',
            parentId: '687',
            children: [
              {
                label: '杭州市',
                id: '330100',
                parentId: '687',
                children: [
                  {
                    label: '杭州市',
                    id: '330100',
                    parentId: '687',
                    children: [
                      {
                        label: '杭州市',
                        id: '330100',
                        parentId: '687',
                        children: [
                          {
                            label: '杭州市',
                            id: '330100',
                            parentId: '687',
                            children: [{ label: '杭州市', id: '330100', parentId: '687' }]
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  },
  {
    label: '江苏省',
    id: '320000',
    parentId: '1231312',
    children: [{ label: '南京市', id: '320100', parentId: '3435', children: [] }]
  }
];
const loading = ref(false);
const finish = ref(false);
const treeData = ref([]);
const onLoad = () => {
  loading.value = true;
  applyList();
  loading.value = false;
};
const applyList = async () => {
  // eslint-disable-next-line no-unused-vars
  const postEiInfo = new EiInfo();
  await api4j.RCRM0103_zcTree(postEiInfo).then((res) => {
    console.log('data:', res);
    console.log('data2:', res.extAttr.treeData);
    treeData.value = res.extAttr.treeData;
    // 处理每个顶级节点 删除空数组Children
    treeData.value.forEach((node) => {
      removeEmptyChildren(node);
    });
  });
};
// 递归删除空数组Children
function removeEmptyChildren(node) {
  if (node.children && node.children.length > 0) {
    // 递归处理子节点
    node.children.forEach((child) => {
      removeEmptyChildren(child);
    });
  } else {
    // 删除children为空数组的属性
    delete node.children;
  }
}
const zcID = ref('');

// 全部选项选择完毕后，会触发 finish 事件
const onFinish1 = ({ selectedOptions }) => {
  console.log('select1:', selectedOptions);
  console.log('----------');
  console.log('最后一条数据:', selectedOptions[selectedOptions.length - 1]);
  console.log('最后一条数据value:', selectedOptions[selectedOptions.length - 1].id);
  // 等于空
  zcDatas = [];
  zcID.value = '';
  dataList.value = [];
  // 存放资产id
  if (![selectedOptions.length - 1] == '') {
    //  如果不存在 才push
    if (
      !zcDatas.includes(
        selectedOptions[selectedOptions.length - 1].id +
          '=' +
          selectedOptions.map((option) => option.label).join('/')
      )
    ) {
      zcDatas.push(
        selectedOptions[selectedOptions.length - 1].id +
          '=' +
          selectedOptions.map((option) => option.label).join('/')
      );
      // 查询资产表
      console.log('===', selectedOptions[selectedOptions.length - 1].id);
      zcID.value = selectedOptions[selectedOptions.length - 1].id;
    }
  }
  show1.value = false;
  fieldValue1.value = selectedOptions.map((option) => option.label).join('/');
};

const val8 = ref('');
const show8 = reactive([]);
const dataList = ref([]);
const onConfirm8 = (value, index) => {
  show8[0] = false;
  val8.value = value;
  Toast(`当前资产名称: ${value}`);
};
const onChange8 = (value, index) => {
  Toast(`当前资产名称: ${value}`);
};
const onCancel8 = () => {
  show8.forEach((item, index) => {
    show8[index] = false;
    val8.value = '';
  });
};
// 选择资产
const sleectByZcId = async () => {
  if (zcID.value == '') {
    Toast('请先选择楼层');
    show8[0] = false;
    return;
  }
  const postEiInfo = new EiInfo();
  postEiInfo.set('zcID', zcID.value);
  await api4j.RCRM0103_zcIdQuery(postEiInfo).then((res) => {
    if (res.status == 1) {
      console.log('res', res);
      zcData = res.extAttr.zcData;
      dataList.value = zcData.map((item) => item.assetName);
    }
  });
};

const shows = ref(false);
const showPopup = () => {
  shows.value = true;
};
const qr = () => {
  // 如果数据为空
  if (zcDatas.length === 0) {
    Toast('请选择楼层');
    return;
  }
  shows.value = false;
};
// 资产清除
const zcClear = () => {
  cascaderValue1.value = '';
  fieldValue1.value = '';
  // 清空资产
  zcData = [];
  zcDatas = [];
  zcID.value = '';
  val8.value = '';
};

// 定义规则
const fieldNames = {
  text: 'label',
  value: 'id',
  children: 'children'
};
const show1 = ref(false);
const cascaderValue1 = ref('');
const cascaderValue2 = ref('');
const cascaderValue3 = ref('');
const cascaderValue4 = ref('');
const cascaderValue5 = ref('');
const cascaderValue6 = ref('');
const cascaderValue7 = ref('');
const cascaderValue8 = ref('');
const cascaderValue9 = ref('');
const fieldValue1 = ref('');
const clearData = () => {
  cascaderValue1.value = '';
  cascaderValue2.value = '';
  cascaderValue3.value = '';
  cascaderValue4.value = '';
  cascaderValue5.value = '';
  cascaderValue6.value = '';
  cascaderValue7.value = '';
  cascaderValue8.value = '';
  cascaderValue9.value = '';
};
// const timeI = ref(10);
// const canClick = ref(true);
// function time1() {
//   if (canClick.value === false) return;
//   canClick.value = false;
//   timeI.value = 10;
//   setInterval(function () {
//     console.log(11111111)
//     label1.value = timeI.value + 's';
//     timeI.value--;
//     if (timeI.value <= 0) {
//       label1.value = '发送';
//       canClick.value = true;
//       stop();
//     }
//   }, 1000);
// }
const label1 = ref('发送');
</script>
<template>
  <div>
    <div>
      <div
        style="
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          background: #4b75e5;
          height: 65px;
          color: white;
          z-index: 1000;
        "
      >
        <div style="font-size: 20px; padding-top: 20px; text-align: center">资产绑定</div>
      </div>
    </div>
    <van-list
      v-model:loading="loading"
      class="working-list"
      :finished="finish"
      finished-text=""
      offset="1"
      @load="onLoad"
    >
      <van-form class="form-card" style="margin-top: 75px" @submit="onSubmit">
        <van-cell-group class="form-cell-group" inset>
          <van-field required label="楼层名称：" placeholder="请选择楼层" center>
            <template #input>
              <van-cell is-link @click="showPopup">{{
                fieldValue1 == '' ? '请选择楼层' : fieldValue1
              }}</van-cell>
            </template>
          </van-field>
          <van-popup
            v-model:show="shows"
            class="form-cell-group"
            closeable
            close-icon="close"
            position="bottom"
            close-icon-position="top-right"
            close-icon-size="100px"
            :style="{ width: '100%', height: '80%' }"
            :close="clearData()"
          >
            <div style="margin-top: 50px; margin-left: 16px; display: flex">
              <span style="color: red; margin-top: 9px; margin-right: 2px">*</span>
              <span style="margin-top: 6px">楼层</span>
              <van-button
                type="default"
                icon="delete-o"
                size="small"
                style="margin-left: 170px"
                plain
                @click="zcClear"
                >清除记录</van-button
              >
            </div>
            <van-field
              v-model="fieldValue1"
              is-link
              readonly
              label=""
              placeholder="请选择楼层"
              style="margin-top: 15px"
              @click="show1 = true"
            />
            <van-popup v-model:show="show1" round position="bottom">
              <van-cascader
                v-model="cascaderValue1"
                title="请选择楼层"
                :options="treeData"
                :field-names="fieldNames"
                @close="show1 = false"
                @finish="onFinish1"
              />
            </van-popup>

            <van-button
              style="margin-top: 30px; background-color: #4b75e5"
              type="primary"
              block
              @click="qr()"
              >确认</van-button
            >
          </van-popup>
          <van-field
            v-model="val8"
            class="titles"
            label="资产名称:"
            placeholder="请选择资产名称"
            required
            center
          >
            <template #input>
              <van-cell :value="val8" is-link @click="show8[0] = true">
                {{ val8 == '' || val8 == undefined ? '请选择资产' : val8 }}
              </van-cell>
              <van-popup position="bottom" :show="show8[0]" @open="sleectByZcId()">
                <van-picker
                  title="资产名称"
                  :columns="dataList"
                  @confirm="onConfirm8"
                  @cancel="onCancel8"
                  @change="onChange8"
                />
              </van-popup>
            </template>
          </van-field>
          <van-field v-model="username" required label="业主姓名：" placeholder="请输入姓名" />
          <van-field
            v-model="tel"
            type="digit"
            required
            label="业主电话："
            placeholder="请输入电话"
          />
        </van-cell-group>
        <van-button
          native-type="submit"
          round
          style="background-color: #4b75e5; color: white; width: 90%; margin: 0 auto"
          block
          >保存</van-button
        >
      </van-form>
    </van-list>
  </div>
</template>

<style lang="stylus" scoped>
.page-main

  .working-list
    .item1
      padding-top 0px
      padding-bottom 0px
    .title1
      color #003586
      font-weight bolder
      font-size 13px
    .titles
      color #161718
      font-weight bolder
      font-size 13px
    .titless
      color #161718
      font-weight bolder
      font-size 17px
    .title2
      color #808080
      font-size 13px
    padding 4px
    margin-bottom 48px
    .van-tag
      margin-left 5px
      font-size 12px
      padding 5px
    .btn1
      background-color #038008
      border-radius 5px
      margin-left 5px
    .btn0
      background-color #ff8d1a
      border-radius 5px
      margin-left 5px
    .class1
      background-color #99bcf1
      border-radius 5px
    .class2
      background-color #f19999
      border-radius 5px
    .class3
      background-color #99a6f1
      border-radius 5px
    .card-item
      margin 8px
      background-color white

      .item-value
        display flex
        justify-content space-between
        overflow hidden
        text-overflow ellipsis
        word-break keep-all
        white-space nowrap
        background-color transparent
        .group1
          display flex
          flex-direction row
          justify-content space-between

  .bottom-buttons
    position fixed
    bottom 12px
    left auto
    width 100%
    max-width var(--max-width)
</style>
